<template>
  <div class="admin-tasks">
    <el-card>
      <template #header>
        <span>任务管理</span>
      </template>
      
      <!-- 搜索筛选 -->
      <div class="search-section">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-input
              v-model="filters.keyword"
              placeholder="搜索任务标题"
              @keyup.enter="loadTasks"
            />
          </el-col>
          <el-col :span="6">
            <el-select v-model="filters.status" placeholder="任务状态" clearable>
              <el-option label="待解决" :value="0" />
              <el-option label="已关闭" :value="1" />
              <el-option label="解决中" :value="2" />
              <el-option label="已完成" :value="3" />
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-select v-model="filters.schoolId" placeholder="选择学校" clearable>
              <el-option
                v-for="school in schools"
                :key="school.id"
                :label="school.name"
                :value="school.id"
              />
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-button type="primary" @click="loadTasks">搜索</el-button>
            <el-button @click="resetFilters">重置</el-button>
          </el-col>
        </el-row>
      </div>
      
      <!-- 任务列表 -->
      <el-table :data="tasks" v-loading="loading">
        <el-table-column prop="title" label="任务标题" />
        <el-table-column prop="publisherName" label="发布者" />
        <el-table-column prop="accepterName" label="接受者" />
        <el-table-column prop="schoolName" label="学校" />
        <el-table-column prop="reward" label="奖励">
          <template #default="{ row }">
            ¥{{ row.reward }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="发布时间" width="150" />
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button
              v-if="row.status === 1"
              size="small"
              type="danger"
              @click="deleteTask(row)"
            >
              删除
            </el-button>
            <el-button
              v-if="row.status !== 1"
              size="small"
              type="warning"
              @click="closeTask(row)"
            >
              关闭
            </el-button>
            <span v-if="row.status === 1" class="text-gray-400">-</span>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination" v-if="tasks.length > 0">
        <el-pagination
          :current-page="currentPage"
          :page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="loadTasks"
          @current-change="loadTasks"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import api from '../../utils/api'

const loading = ref(false)
const tasks = ref([])
const schools = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

const filters = reactive({
  keyword: '',
  status: '',
  schoolId: ''
})

const getStatusText = (status) => {
  const statusMap = {
    0: '待解决',
    1: '已关闭',
    2: '解决中',
    3: '已完成'
  }
  return statusMap[status] || '未知'
}

const getStatusType = (status) => {
  const typeMap = {
    0: 'warning',
    1: 'info',
    2: 'primary',
    3: 'success'
  }
  return typeMap[status] || 'info'
}

const loadTasks = async () => {
  loading.value = true
  try {
    const response = await api.get('/admin/tasks')
    if (response.data.code === 200) {
      tasks.value = response.data.data
      total.value = response.data.data.length
    }
  } catch (error) {
    ElMessage.error('加载任务失败')
  } finally {
    loading.value = false
  }
}

const loadSchools = async () => {
  try {
    const response = await api.get('/auth/schools')
    if (response.data.code === 200) {
      schools.value = response.data.data
    }
  } catch (error) {
    console.error('加载学校列表失败:', error)
  }
}

const resetFilters = () => {
  filters.keyword = ''
  filters.status = ''
  filters.schoolId = ''
  loadTasks()
}

const deleteTask = async (task) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除任务"${task.title}"吗？此操作不可恢复！`,
      '确认删除',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await api.delete(`/admin/tasks/${task.id}`)
    if (response.data.code === 200) {
      ElMessage.success('任务删除成功')
      // 重新加载任务列表
      loadTasks()
    } else {
      ElMessage.error(response.data.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const closeTask = async (task) => {
  try {
    await ElMessageBox.confirm('确定要关闭这个任务吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 调用API关闭任务
    const response = await api.put(`/admin/tasks/${task.id}/close`)
    if (response.data.code === 200) {
      ElMessage.success('任务已关闭')
      // 重新加载任务列表
      loadTasks()
    } else {
      ElMessage.error(response.data.message || '关闭失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
    }
  }
}

onMounted(() => {
  loadTasks()
  loadSchools()
})
</script>

<style scoped>
.admin-tasks {
  padding: 20px;
}

.text-gray-400 {
  color: #9ca3af;
  font-size: 12px;
}

.search-section {
  margin-bottom: 20px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 4px;
}

.pagination {
  margin-top: 20px;
  text-align: center;
}
</style>
